// Webhook路由：接收外部系统的事件通知，或向外部系统发送通知
const express = require('express');
const router = express.Router();
const https = require('https');
const http = require('http');

// 发送Webhook通知 (当词条状态变更或发布完成时调用)
async function sendWebhook(url, event, data) {
  try {
    const urlObj = new URL(url);
    const client = urlObj.protocol === 'https:' ? https : http;
    
    return new Promise((resolve, reject) => {
      const postData = JSON.stringify({
        event,
        timestamp: new Date().toISOString(),
        data
      });

      const options = {
        hostname: urlObj.hostname,
        port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
        path: urlObj.pathname,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Webhook-Event': event,
          'Content-Length': Buffer.byteLength(postData)
        }
      };

      const req = client.request(options, (res) => {
        let responseData = '';
        res.on('data', (chunk) => {
          responseData += chunk;
        });
        res.on('end', () => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
            resolve(JSON.parse(responseData || '{}'));
          } else {
            reject(new Error(`Webhook请求失败: ${res.statusCode} ${res.statusMessage}`));
          }
        });
      });

      req.on('error', (error) => {
        reject(error);
      });

      req.write(postData);
      req.end();
    });
  } catch (error) {
    console.error('Webhook发送失败', error);
    throw error;
  }
}

module.exports = router;
module.exports.sendWebhook = sendWebhook;
